package com.demo.file.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class FileUploadController {

    @GetMapping("/")
    public ModelAndView file(ModelAndView modelAndView) {
        modelAndView.setViewName("file-upload");
        return modelAndView;
    }

    @GetMapping("/result")
    public ModelAndView result(String message, ModelAndView modelAndView) {
        modelAndView.setViewName("upload-result");
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    @PostMapping("/upload")
    public ModelAndView saveFile(MultipartFile file, ModelAndView modelAndView) {
        modelAndView.addObject("message", "后端信息");
        if (file == null) {
            modelAndView.setViewName("redirect:result");
//            redirectAttributes.addAttribute("message", "文件为空");
//            return "redirect:/result";
        }

        String fileName = file.getOriginalFilename();
        String folder = "D:/temp/";
        Path path = Paths.get(folder + fileName);
        try {
            byte[] bytes = file.getBytes();
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        redirectAttributes.addAttribute("message", "操作成功");
//        return "redirect:/result";
        modelAndView.setViewName("redirect:result");
        return modelAndView;
    }
}
